package com.demo.shiro;

import javax.annotation.Resource;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import com.demo.entity.User;
import com.demo.service.UserService;

public class ShiroRealm extends AuthorizingRealm {

	@Resource  
    private UserService userService;  
  
	@Override
	public void setName(String name) {
	  super.setName(this.getClass().getName());
	}
	
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(
			PrincipalCollection principals) {
		return null;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken authcToken) throws AuthenticationException {
		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
		User user = new User();
		user.setUsername(token.getUsername());
		user = userService.selectOne(user);
		if (user != null) {
			return new SimpleAuthenticationInfo(user.getUsername(), user.getPassword().toCharArray(),
					 	  user.getRealname());
		} else {
			return null;
		}
	}
}
